package com.hqu.environment.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.hqu.environment.annotation.LoginUser;
import com.hqu.environment.constant.Constant;
import com.hqu.environment.dao.AuthorityDao;
import com.hqu.environment.dao.ElementStatusDao;
import com.hqu.environment.dao.EquipmentCategoryDao;
import com.hqu.environment.dao.EquipmentDao;
import com.hqu.environment.dao.FarmCategoryDao;
import com.hqu.environment.dao.FarmDao;
import com.hqu.environment.dao.TimeValueDao;
import com.hqu.environment.dto.AuthorityDTO;
import com.hqu.environment.dto.ElementStatusDTO;
import com.hqu.environment.dto.EquipmentCategoryDTO;
import com.hqu.environment.dto.EquipmentDTO;
import com.hqu.environment.dto.FarmCategoryDTO;
import com.hqu.environment.dto.FarmDTO;
import com.hqu.environment.dto.FarmEquipmentDTO;
import com.hqu.environment.dto.TimeValueDTO;
import com.hqu.environment.entity.EquipmentCategory;
import com.hqu.environment.entity.TimeValue;
import com.hqu.environment.utils.QRCodeUtil;
import com.hqu.environment.utils.Result;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Description: 农场Controller
 * @Date: 2019/04/25 22:15
 * @Author: 邓勇嘉
 **/
@Controller
@RequestMapping("admin/farm")
public class AdminFarmController {

    @Autowired
    FarmDao farmDao;
    @Autowired
    EquipmentDao equipmentDao;
    @Autowired
    FarmCategoryDao farmCategoryDao;
    @Autowired
    AuthorityDao authorityDao;
    @Autowired
    ElementStatusDao elementStatusDao;
    @Autowired
    EquipmentCategoryDao equipmentCategoryDao;
    @Autowired
    TimeValueDao timeValueDao;
    @Autowired
    SqlSession sqlSession;


    @RequestMapping("/getFarmPageInfo")
    @ResponseBody
    public Result getFarmPageInfo() {
        List<FarmCategoryDTO> fc=farmCategoryDao.selectList(null);
        List<AuthorityDTO> a = authorityDao.selectList();
        EquipmentDTO equipmentDTO = new EquipmentDTO();
        equipmentDTO.setId(1);
        List<EquipmentDTO> e = equipmentDao.selectList(equipmentDTO);

        return Result.success().add("farmCategoryList",fc).add("authorityList",a).add("equipmentList",e);
    }

    @RequestMapping("/getList")
    @ResponseBody
    public Result getFarmList(FarmDTO farmDTO) {
        List<FarmDTO> farmList = farmDao.selectList(farmDTO);
        return Result.success().add("farmList",farmList);
    }

    @RequestMapping("/getById")
    @ResponseBody
    public Result getFarmById(Integer id) {
        FarmDTO farmDTO = farmDao.selectByPrimaryKey(id);
        return Result.success().add("farm",farmDTO);
    }

    @RequestMapping("/deleteById")
    @ResponseBody
    public Result deleteById(Integer id) {
        farmDao.deleteByPrimaryKey(id);
        farmDao.deleteFarmEquipmentByFarmId(id);
        return Result.success();
    }


    @RequestMapping("/add")
    @ResponseBody
    public Result addFarm(@LoginUser Integer userId, @RequestBody FarmDTO farmDTO) throws Exception {
        farmDTO.setCreator(userId);
        farmDTO.setCreateTime(new Date());
        farmDao.insertSelective(farmDTO);

        String s="{\"id\":\""+farmDTO.getId()+"\",\"type\":\"farm\"}";
        String codeUrl= QRCodeUtil.encode(s, Constant.DEST+Constant.LOGO,Constant.DEST,true);
        FarmDTO farmDTOwithCodeUrl=new FarmDTO();
        farmDTOwithCodeUrl.setId(farmDTO.getId());
        farmDTOwithCodeUrl.setCodeUrl(codeUrl);
        farmDao.updateByPrimaryKeySelective(farmDTOwithCodeUrl);

        FarmDao farmDaoSqlSession=sqlSession.getMapper(FarmDao.class);
        for(EquipmentDTO e : farmDTO.getEquipmentList()){
            farmDaoSqlSession.insertFarmEquipment(new FarmEquipmentDTO(farmDTO.getId(),e.getId()));
        }

        initMonitor(farmDTO);
        simulateTimeValue(farmDTO);

        return Result.success();
    }

    @RequestMapping("/update")
    @ResponseBody
    public Result updateFarm(@LoginUser Integer userId, @RequestBody FarmDTO farmDTO) {
        farmDTO.setCreator(userId);
        farmDTO.setCreateTime(new Date());
        farmDao.updateByPrimaryKeySelective(farmDTO);
        farmDao.deleteFarmEquipmentByFarmId(farmDTO.getId());
        FarmDao farmDaoSqlSession=sqlSession.getMapper(FarmDao.class);
        for(EquipmentDTO e : farmDTO.getEquipmentList()){
            farmDaoSqlSession.insertFarmEquipment(new FarmEquipmentDTO(farmDTO.getId(),e.getId()));
        }
        return Result.success();
    }

    @RequestMapping("/deleteList")
    @ResponseBody
    public Result deleteFarmList(String ids) {
        List <Integer> list = JSONObject.parseArray(ids,Integer.class);
        farmDao.delete(list);
        farmDao.deleteFarmEquipmentList(list);
        return Result.success();
    }


    private void initMonitor(FarmDTO farmDTO){
        List<EquipmentCategoryDTO> ec=equipmentCategoryDao.selectList(null);
        for(EquipmentCategoryDTO item: ec){
            ElementStatusDTO elementStatusDTO = new ElementStatusDTO();
            elementStatusDTO.setFarm(farmDTO.getId());
            elementStatusDTO.setMonitorMax(item.getMaxLimit());
            elementStatusDTO.setMonitorMin(item.getMinLimit());
            elementStatusDTO.setSettingValue((item.getMaxLimit()+item.getMinLimit())/2);
            elementStatusDTO.setValue((item.getMaxLimit()+item.getMinLimit())/2);
            elementStatusDTO.setEquipmentCategory(item.getId());
            elementStatusDao.insertSelective(elementStatusDTO);
        }
    }

    private void simulateTimeValue(FarmDTO farmDTO) throws ParseException {
        List<EquipmentCategoryDTO> ec=equipmentCategoryDao.selectList(null);
        Date date=getTimePeriod();

        for(EquipmentCategoryDTO item: ec){
            TimeValueDTO timeValueDTO = new TimeValueDTO();
            timeValueDTO.setFarm(farmDTO.getId());
            timeValueDTO.setTime(date);
            timeValueDTO.setEquipmentCategory(item.getId());
            timeValueDTO.setValue((item.getMaxLimit()+item.getMinLimit())/2);
            timeValueDao.insertSelective(timeValueDTO);
        }


    }

    private Date getTimePeriod(){
        try {
            long now = System.currentTimeMillis();
            SimpleDateFormat sdfOne = new SimpleDateFormat("yyyy-MM-dd");
            long weeHours=sdfOne.parse(sdfOne.format(now)).getTime();
            long overTime = (now - weeHours);
            long temp=overTime/ Constant.THREE_HOUR *Constant.THREE_HOUR;
            return new Date(weeHours+temp);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }

    }
}
